package club.cearnach.api.util;

import club.cearnach.api.exception.MoviePathException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author 阮胜
 * @date 2018/5/20 14:18
 */
public class FileUtil {
    public static String saveFile(MultipartFile file, String uploadPath) throws MoviePathException, IOException {
        File path = new File(uploadPath);
        if (!path.exists()) {
            if (!path.mkdirs() && !path.isDirectory()) {
                throw new MoviePathException(MoviePathException.UPLOAD_PATH_CAN_NOT_FOUND);
            }
        }
        String realName = GlobalUtil.randomId() + file.getOriginalFilename();
        String fileName = uploadPath + realName;
        File newFile = new File(fileName);
        file.transferTo(newFile);
        return realName;
    }
}
